package com.crr.common.controller;

import com.crr.common.bean.ResultBean;
import com.crr.common.excep.ValidateException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class BaseController {
    //状态码 success成功200 fail失败0
    private final int SUCCESS = 200;
    private final int FAIL = 0;

    /**
     * 响应成功
     *
     * @param msg 消息描述
     * @return
     */
    protected ResultBean success(String msg) {
        return convert(SUCCESS, msg, null);
    }

    protected ResultBean success(String msg, Object data) {
        return convert(SUCCESS, msg, data);
    }

    /**
     * 响应失败
     *
     * @param msg
     * @return
     */
    protected ResultBean fail(String msg) {
        return convert(FAIL, msg, null);
    }

    protected ResultBean fail(String msg, Object data) {
        return convert(FAIL, msg, data);
    }

    /**
     * 转换成统一结果
     *
     * @param code
     * @param msg
     * @param data
     * @return
     */
    ResultBean convert(int code, String msg, Object data) {
        return new ResultBean(code, msg, data);
    }

    /**
     * 保存结果
     * @param res
     * @return
     */
    protected ResultBean saveResult(int res) {
        return (res == 1) ? success("保存成功") : fail("保存失败");
    }

    protected ResultBean updateResult(int res) {
        return (res == 1) ? success("修改成功") : fail("修改失败");
    }

    protected ResultBean deleteResult(int res) {
        return (res == 1) ? success("删除成功") : fail("删除失败");
    }
    protected ResultBean validate(BindingResult result){
        List<FieldError> fieldErrors= result.getFieldErrors();
        if(fieldErrors.size()>0){
            Map<String,String> error=new HashMap<>();
            fieldErrors.forEach(e->{
                error.put(e.getField(),e.getDefaultMessage());
            });

           throw new ValidateException(error);
        }
        return null;
    }

}
